import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { useDeepCompareEffect } from 'ahooks';
import { Button, Col, Form, Modal, Row, Space, TimePicker } from 'antd';
import type { FC } from 'react';
import type { TPickerItem } from './types';

type TProps = {
  visible: boolean;
  onSubmit: TAnyFunction;
  onCancel: TAnyFunction;
  data: TPickerItem[];
};

const format = 'HH:mm';

const TimeRangePickerModal: FC<TProps> = (props) => {
  const { visible, onSubmit, onCancel, data } = props;
  const [formRef] = Form.useForm();

  const handleSubmit = () => {
    if (formRef) {
      formRef.submit();
    }
  };

  const handleFinish = (val: { timePeriods: TPickerItem[] }) => {
    onSubmit?.(val.timePeriods);
  };

  useDeepCompareEffect(() => {
    if (data) {
      formRef.setFieldsValue({
        timePeriods: data,
      });
    }
  }, [data]);

  return (
    <Modal title="自定义时间段" open={visible} width={600} onCancel={onCancel} onOk={handleSubmit}>
      <Row>
        <Col span={15}>
          <Form form={formRef} onFinish={handleFinish} autoComplete="off">
            <Form.List name="timePeriods">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, ...restField }, idx) => (
                    <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                      <Form.Item
                        {...restField}
                        label={`时间段${idx + 1}`}
                        name={[name, 'timeRange']}
                        rules={[{ required: true, message: '请选择时间段' }]}
                      >
                        <TimePicker.RangePicker
                          // defaultValue={[moment('00:00', format), moment('23:59', format)]}
                          format={format}
                        />
                      </Form.Item>
                      <MinusCircleOutlined onClick={() => remove(name)} />
                    </Space>
                  ))}
                  <Form.Item>
                    <Button
                      className="f-tal"
                      type="dashed"
                      onClick={() => add()}
                      block
                      icon={<PlusOutlined />}
                    >
                      继续添加
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </Form>
        </Col>
      </Row>
    </Modal>
  );
};

export default TimeRangePickerModal;
